﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FFS.Model;
using FFS.BLL;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace FFS
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        SystemLogService slService = new SystemLogService();
        SysRemindService remindService = new SysRemindService();
        List<SysRemindInfo> currentRemindInfo = new List<SysRemindInfo>();

        /// <summary>
        /// 检查当前窗体菜单是否已经打开过
        /// </summary>
        /// <param name="MdiChildrenClassName"></param>
        /// <param name="FunctionName"></param>
        /// <returns></returns>
        private bool OnlyOpenOneMdiWindow(string MdiChildrenClassName, string FunctionName)
        {
            foreach (Form childForm in this.MdiChildren)
            {
                if (childForm.Name == MdiChildrenClassName)
                {
                    childForm.Activate();
                    childForm.WindowState = FormWindowState.Maximized;
                    return true;
                }
            }

            return false;
        }

        private void tsm_ShowHelp_Click(object sender, EventArgs e)
        {
            if (System.IO.File.Exists(System.IO.Path.Combine(Application.StartupPath, "help.txt")))
            {
                Help.ShowHelp(this, "help.txt");
            }
            else
            {
                Help.ShowPopup(this,"家庭财务管理系统",new Point(500,500));
            }
        }

        private void tsm_ShowAbout_Click(object sender, EventArgs e)
        {
            if (!OnlyOpenOneMdiWindow("frmAbout", this.tsm_ShowAbout.Text))
            {
                frmAbout about = new frmAbout();
                about.ShowDialog();
            }
        }

        private void tsm_ShowLeftMenu_Click(object sender, EventArgs e)
        {
            this.panel_LeftMenu.Visible = !this.panel_LeftMenu.Visible;
            this.tsm_ShowLeftMenu.Checked = this.panel_LeftMenu.Visible;
        }

        private void tsm_StatusStrip_Click(object sender, EventArgs e)
        {
            this.statusStrip_buttom.Visible = !this.statusStrip_buttom.Visible;
            this.tsm_StatusStrip.Checked = this.statusStrip_buttom.Visible;
        }

        private void tsm_CloseAllMdiChildrenForm_Click(object sender, EventArgs e)
        {
            foreach (Form childFrm in this.MdiChildren)
            {
                if (childFrm != null)
                {
                    childFrm.Close();
                }
            }

            MessageBox.Show("已经关闭所有子窗体");
        }

        private void tsm_HengPaiWindows_Click(object sender, EventArgs e)
        {
            this.tsm_HengPaiWindows.Checked = true;
            this.LayoutMdi(MdiLayout.TileHorizontal);
            this.tsm_ShuPaiWindows.Checked = false;
            this.tsm_CengDieWindows.Checked = false;
        }

        private void tsm_ShuPaiWindows_Click(object sender, EventArgs e)
        {
            this.tsm_ShuPaiWindows.Checked = true;
            this.LayoutMdi(MdiLayout.TileVertical);
            this.tsm_HengPaiWindows.Checked = false;
            this.tsm_CengDieWindows.Checked = false;
        }

        private void tsm_CengDieWindows_Click(object sender, EventArgs e)
        {
            this.tsm_CengDieWindows.Checked = true;
            this.LayoutMdi(MdiLayout.Cascade);
            this.tsm_ShuPaiWindows.Checked = false;
            this.tsm_HengPaiWindows.Checked = false;
        }

        private void btn_menu_ChangYongFunction_Click(object sender, EventArgs e)
        {
            this.btn_menu_FuZhuFunction.Dock = DockStyle.Bottom;
            this.btn_menu_SystemSetting.Dock = DockStyle.Bottom;

            this.btn_menu_ChangYongFunction.Dock = DockStyle.Top;
            this.listView_SubMenu.Items.Clear();
            this.listView_SubMenu.LargeImageList = this.imageList_SubMenuImage;
            this.listView_SubMenu.Items.Add("tsm_FinanceItemManage", "财务项目管理", 0);
            this.listView_SubMenu.Items.Add("tsm_FamilyMemberManage", "家庭成员管理", 1);
            this.listView_SubMenu.Items.Add("tsm_FinanceDetailManage", "收支明细管理", 2);
            this.listView_SubMenu.Items.Add("tsm_LoginUserManage", "登陆用户管理", 3);
            this.listView_SubMenu.Items.Add("tsm_ModifyUserPassword", "修改用户密码", 4);
            this.listView_SubMenu.Items.Add("tsm_QiHuanLoginUser", "切换登陆账户", 0);
        }

        private void tsm_FinanceItemManage_Click(object sender, EventArgs e)
        {
            if (!OnlyOpenOneMdiWindow("frmFinanceItem", "财务项目管理"))
            {
                frmFinanceItem frmFinanceItem = new frmFinanceItem();
                frmFinanceItem.MdiParent = this;
                frmFinanceItem.WindowState = FormWindowState.Maximized;
                frmFinanceItem.Show();
            }
        }

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void tsm_Exit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void tsm_context_ExitSystem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void tsm_menu_StepOutSystem_Click(object sender, EventArgs e)
        {
            frmLeavingSystem fls = new frmLeavingSystem();
            fls.ShowDialog();
        }

        private void tsm_context_StepOutSystem_Click(object sender, EventArgs e)
        {
            tsm_menu_StepOutSystem_Click(sender,e);
        }

        private void tsm_FamilyMemberManage_Click(object sender, EventArgs e)
        {
            if (!OnlyOpenOneMdiWindow("frmFamilyMember","家庭成员管理"))
            {
                frmFamilyMember form_familyMember = new frmFamilyMember();
                form_familyMember.MdiParent = this;
                form_familyMember.WindowState = FormWindowState.Maximized;
                form_familyMember.Show();
            }
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("您确定要退出系统吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                slService.ManageSystemLog().CreateLoginUserActionLog(Context._Login_UserName, "Login", "Exit System", Context._Login_UserName);
                e.Cancel = false;
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            this.tssl_LoginUser.Text = "登陆用户：" + FFS.Model.Context._Login_UserName;
            this.tssl_LoginDatetime.Text = "登陆时间：" + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString();

            this.btn_menu_ChangYongFunction_Click(sender,e);

            this.tssl_LoginUser.Width = this.Width / 3;
            this.tssl_LoginDatetime.Width = this.Width / 3;
            this.tssl_CurrentDatetime.Width = this.Width / 3;

            this.tsm_CengDieWindows_Click(sender,e);

            this.notifyIcon.Visible = false;

            this.WindowState = FormWindowState.Maximized;

            /*反序列化登陆用户信息*/
            IFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream("myBinary.bin",FileMode.Open,FileAccess.Read,FileShare.Read);
            Context context = (Context)formatter.Deserialize(stream);

            

        }

        private void timer_frmMain_Tick(object sender, EventArgs e)
        {
            this.Opacity += 0.1;
            if(this.Opacity == 1)
            {
                this.timer_frmMain.Dispose();
            }
        }

        private void timer_DatetimeFresh_Tick(object sender, EventArgs e)
        {
            this.tssl_CurrentDatetime.Text = "当前时间：" + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString();

            //提醒信息弹出
            currentRemindInfo = remindService.ManageSysRemind().GetCurrentSysRemind(DateTime.Now);
            if (currentRemindInfo.Count > 0)
            {
                this.tsmi_ViewCurrentRemind.Text = "提醒信息(" + currentRemindInfo.Count.ToString() + ")";
                this.tsmi_ViewCurrentRemind.ForeColor = Color.Red;
                //this.tsmi_ViewCurrentRemind.Font.Bold = true;
                foreach (SysRemindInfo remind in currentRemindInfo)
                {
                    if (remind.RemindType == "提醒一次")
                    {
                        remindService.ManageSysRemind().UpdateSysRemindStatus(remind.SysRemindID, true, Context._Login_UserName);
                        MessageBox.Show(remind.RemindContent.ToString());
                    }
                }
            }
            else 
            {
                this.tsmi_ViewCurrentRemind.Text = "提醒信息(0)";
                this.tsmi_ViewCurrentRemind.ForeColor = Color.Black;
                //this.tsmi_ViewCurrentRemind.Font.Bold = false;
            }

        }

        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Maximized;
                this.Activate();
                this.notifyIcon.Visible = false;
                this.ShowInTaskbar = true;
            }
        }

        private void frmMain_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.notifyIcon.Visible = true;
                this.ShowInTaskbar = false;
            }

            this.tssl_LoginUser.Width = this.Width / 3;
            this.tssl_LoginDatetime.Width = this.Width / 3;
            this.tssl_CurrentDatetime.Width = this.Width / 3;
            
        }

        private void listView_SubMenu_DoubleClick(object sender, EventArgs e)
        {
            string seletedMenu = listView_SubMenu.SelectedItems[0].Text;
            switch (seletedMenu)
            {
                case "财务项目管理":
                    this.tsm_FinanceItemManage_Click(sender,e);
                    break;
                case "家庭成员管理":
                    this.tsm_FamilyMemberManage_Click(sender,e);
                    break;
                case "收支明细管理":
                    this.tsm_FinanceDetailManage_Click(sender, e);
                    break;
                case "登陆用户管理":
                    this.tsm_LoginUserManage_Click(sender,e);
                    break;
                case "修改用户密码":
                    this.tsm_ModifyUserPassword_Click(sender,e);
                     break;
                case "切换登陆账户":
                     this.tsm_ChangeLoginUser_Click(sender,e);
                     break;
                case "系统参数设置":
                     this.tsm_menu_SystemParameterManage_Click(sender, e);
                     break;
                case "导入导出数据":
                     this.tsm_menu_ImportExportData_Click(sender, e);
                     break;
                case "暂时离开系统":
                     this.tsm_menu_StepOutSystem_Click(sender, e);
                     break;
                case "查看登陆日志":
                     this.tsm_menu_SystemLoginLogManage_Click(sender, e);
                     break;
                case "提醒信息管理":
                     this.tsm_menu_ReminderInfoManage_Click(sender, e);
                     break;
                case "系统数据库备份":
                     this.tsm_menu_SystemBackupManage_Click(sender, e);
                     break;
                case "系统初始化":
                     this.tsm_menu_SytemInit_Click(sender, e);
                     break;
                case "系统数据库连接":
                     this.tsm_menu_DatabaseLinkSetting_Click(sender, e);
                     break;
                default:
                    break;
            }
        }

        private void panel_LeftMenu_SizeChanged(object sender, EventArgs e)
        {
            this.listView_SubMenu.Height = this.panel_LeftMenu.Height - 90;
        }

        private void tsm_LoginUserManage_Click(object sender, EventArgs e)
        {
            if (!OnlyOpenOneMdiWindow("frmLoginUser", "登陆用户管理"))
            {
                frmLoginUser frmloginuser = new frmLoginUser();
                frmloginuser.MdiParent = this;
                frmloginuser.Show();
                //frmloginuser.ShowDialog();
                this.WindowState = FormWindowState.Minimized;
                
            }
        }

        private void btn_menu_FuZhuFunction_Click(object sender, EventArgs e)
        {
            this.btn_menu_SystemSetting.Dock = DockStyle.Bottom;
            this.btn_menu_ChangYongFunction.Dock = DockStyle.Bottom;

            this.btn_menu_FuZhuFunction.Dock = DockStyle.Top;
            this.listView_SubMenu.Items.Clear();
            this.listView_SubMenu.Items.Add("系统数据库备份", "系统数据库备份", 9);
            this.listView_SubMenu.Items.Add("系统初始化", "系统初始化", 10);
            this.listView_SubMenu.Items.Add("系统数据库连接", "系统数据库连接", 11);
            this.listView_SubMenu.Items.Add("打开记事本", "打开记事本", 5);
            this.listView_SubMenu.Items.Add("打开Excel", "打开Excel", 6);
            this.listView_SubMenu.Items.Add("打开Word", "打开Word", 7);
            this.listView_SubMenu.Items.Add("打开计算器", "打开计算器", 8);
        }

        private void btn_menu_SystemSetting_Click(object sender, EventArgs e)
        {
            this.btn_menu_ChangYongFunction.Dock = DockStyle.Bottom;
            this.btn_menu_FuZhuFunction.Dock = DockStyle.Bottom;


            this.btn_menu_SystemSetting.Dock = DockStyle.Top;
            this.listView_SubMenu.Items.Clear();
            this.listView_SubMenu.Items.Add("系统参数置", "系统参数设置", 0);
            this.listView_SubMenu.Items.Add("导入导出数据", "导入导出数据", 1);
            this.listView_SubMenu.Items.Add("暂时离开系统", "暂时离开系统", 2);
            this.listView_SubMenu.Items.Add("查看登陆日志", "查看登陆日志", 3);
            this.listView_SubMenu.Items.Add("提醒信息管理", "提醒信息管理", 4);

        }

        private void tsm_ModifyUserPassword_Click(object sender, EventArgs e)
        {
            if (!OnlyOpenOneMdiWindow("frmModifyLoginPassword", "修改用户密码"))
            {
                frmModifyLoginPassword frmModifyPwd = new frmModifyLoginPassword();
                frmModifyPwd.ShowDialog();
            }
        }

        private void tsm_ChangeLoginUser_Click(object sender, EventArgs e)
        {
            frmChangeLoginUser changeLoginUser = new frmChangeLoginUser();
            changeLoginUser.TopLevel = false;
            changeLoginUser.Parent = this;          
            //changeLoginUser.ShowDialog();
            changeLoginUser.Show();
            
        }

        private void tsm_menu_SystemParameterManage_Click(object sender, EventArgs e)
        {
            if (!OnlyOpenOneMdiWindow("frmSysParameter", "系统参数设置"))
            {
                frmSysParameter frmSysParam = new frmSysParameter();
                frmSysParam.MdiParent = this;
                frmSysParam.WindowState = FormWindowState.Maximized;
                frmSysParam.Show();
            }
        }

        private void tsm_menu_SystemBackupManage_Click(object sender, EventArgs e)
        {
            frmDatabaseBackup backup = new frmDatabaseBackup();
            //backup.Parent = this;
            backup.ShowDialog();
        }

        private void tsm_menu_SytemInit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认要进行系统初始化吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                SystemToolsService sts = new SystemToolsService();
                sts.ManageSystemTools().InitSystem(Context._Login_UserName);
                MessageBox.Show("系统初始化成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void tsm_menu_DatabaseLinkSetting_Click(object sender, EventArgs e)
        {
            try
            {
                SystemToolsService sts = new SystemToolsService();
                if (sts.ManageSystemTools().VerifyDatabaseLinkStatus() == null)
                {
                    MessageBox.Show("数据库连接失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else 
                {
                    MessageBox.Show("数据库连接成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                
            }
            catch (Exception)
            {
                MessageBox.Show("数据库连接失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsm_menu_SystemLoginLogManage_Click(object sender, EventArgs e)
        {
            if (!OnlyOpenOneMdiWindow("frmSystemLog", "查看登陆日志"))
            {
                frmSystemLog fsl = new frmSystemLog();
                fsl.MdiParent = this;
                fsl.WindowState = FormWindowState.Maximized;
                fsl.Show();
            }
        }

        private void tsm_menu_ReminderInfoManage_Click(object sender, EventArgs e)
        {
            if (!OnlyOpenOneMdiWindow("frmSysRemind", "提醒信息管理"))
            {
                frmSysRemind fsr = new frmSysRemind();
                fsr.MdiParent = this;
                fsr.WindowState = FormWindowState.Maximized;
                fsr.Show();
            }
        }

        private void tsmi_ViewCurrentRemind_Click(object sender, EventArgs e)
        {
            foreach (Form childForm in this.MdiChildren)
            {
                if (childForm.Name == "frmSysRemind")
                {
                    childForm.Close();
                    break;
                }
            }

            frmSysRemind frmRemind = new frmSysRemind();
            frmRemind.actionType = "view";
            this.StartPosition = FormStartPosition.CenterParent;
            frmRemind.ShowDialog();
        }

        private void tsm_menu_ImportExportData_Click(object sender, EventArgs e)
        {

        }

        private void tsm_menu_openExcel_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("excel.exe");
        }

        private void tsm_menu_openNotePad_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("notepad.exe");
        }

        private void tsm_menu_openWord_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("winword.exe");
        }

        private void tsm_menu_Calcuator_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("calc.exe");
        }
        
        /// <summary>
        /// 导出数据到Excel
        /// </summary>
        /// <param name="dgv"></param>
        private void ExortExcel(DataGridView dgv)
        {
            //导出到execl    

            try
            {

                SaveFileDialog saveFileDialog = new SaveFileDialog();

                saveFileDialog.Filter = "导出Excel (*.xls)|*.xls";

                saveFileDialog.FilterIndex = 0;

                saveFileDialog.RestoreDirectory = true;

                saveFileDialog.CreatePrompt = true;

                saveFileDialog.Title = "导出文件保存路径";

                saveFileDialog.ShowDialog();

                string strName = saveFileDialog.FileName;

                if (strName.Length != 0)
                {

                    //没有数据的话就不往下执行    

                    if (dgv.Rows.Count == 0)

                        return;



                    // toolStripProgressBar1.Visible = true; 

                    System.Reflection.Missing miss = System.Reflection.Missing.Value;

                    //实例化一个Excel.Application对象 

                    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

                    excel.Application.Workbooks.Add(true);

                    excel.Visible = false;//若是true，则在导出的时候会显示EXcel界面。 

                    if (excel == null)
                    {

                        MessageBox.Show("EXCEL无法启动！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                          
                        return;

                    }

                    Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks;

                    Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss));


                    //Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet;
                    Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSlicer;

                    sheet.Name = "test";

                    //int m = 0, n = 0;

                    //生成Excel中列头名称    

                    for (int i = 0; i < dgv.Columns.Count; i++)
                    {

                        excel.Cells[1, i + 1] = dgv.Columns[i].HeaderText;//输出DataGridView列头名 

                    }

                    //把DataGridView当前页的数据保存在Excel中    

                    for (int i = 0; i < dgv.Rows.Count - 1; i++)
                    {

                        for (int j = 0; j < dgv.Columns.Count; j++)
                        {

                            if (dgv[j, i].ValueType == typeof(string))
                            {

                                excel.Cells[i + 2, j + 1] = "'" + dgv[j, i].Value.ToString();

                            }

                            else
                            {

                                excel.Cells[i + 2, j + 1] = dgv[j, i].Value.ToString();

                            }

                        }

                    }

                    sheet.SaveAs(strName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss);

                    book.Close(false, miss, miss);

                    books.Close();

                    excel.Quit();

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(book);

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(books);

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);

                    GC.Collect();

                    MessageBox.Show("数据已经成功导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    //toolStripProgressBar1.Value = 0; 

                    System.Diagnostics.Process.Start(strName);

                }

            }

            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, "错误提示");

            } 
        }

        private void tsm_FinanceDetailManage_Click(object sender, EventArgs e)
        {
            if (!OnlyOpenOneMdiWindow("frmFinanceDetails", "收支明细管理"))
            {
                frmFinanceDetails frmFinanceDetails = new frmFinanceDetails();
                frmFinanceDetails.MdiParent = this;
                frmFinanceDetails.WindowState = FormWindowState.Maximized;
                frmFinanceDetails.Show();
            }          
        }
    }
}
